package com.ruicar.afs.cloud.apply.contract.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.apply.business.service.ApplySignHistoryService;
import com.ruicar.afs.cloud.apply.business.service.ApplySignRelationService;
import com.ruicar.afs.cloud.apply.common.entity.*;
import com.ruicar.afs.cloud.apply.contract.condition.LoanAppSignPeopleListCondition;
import com.ruicar.afs.cloud.apply.contract.service.ApplyCarInvoiceService;
import com.ruicar.afs.cloud.apply.contract.service.ApplyContractInfoService;
import com.ruicar.afs.cloud.apply.pre.loan.condition.ApplyAppSignAgreeMentCondition;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyAppService;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyCustBaseInfoService;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyOrderInfoService;
import com.ruicar.afs.cloud.bizcommon.print.entity.ComPrintFormManage;
import com.ruicar.afs.cloud.bizcommon.print.service.ComPrintFormManageService;
import com.ruicar.afs.cloud.common.core.security.service.AfsUser;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.BusinessTypeEnum;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.ruicar.afs.cloud.apply.common.utils.ApplyConstants.*;

/**
 * description: 放款签约
 * @date: 2020/8/7 14:28
 * @author mingzhi.li
 */
@Slf4j
@RestController
@RequestMapping("/loanAppSign")
@AllArgsConstructor
public class LoanAppSignController {
    private final ApplyCustBaseInfoService applyCustBaseInfoService;
    private final ComAttachmentFileService attachmentFileService;
    private final ApplyAppService applyAppService;
    private final ApplySignRelationService applySignRelationService;
    private final ApplySignHistoryService applySignHistoryService;
    private final ApplyContractInfoService applyContractInfoService;
    private final ApplyOrderInfoService applyOrderInfoService;
    private final ComPrintFormManageService comPrintFormManageService;
    private final ApplyCarInvoiceService applyCarInvoiceService;

    @RequestMapping(value = "/getLoanAppSignPeopleList", method = RequestMethod.POST)
    @ApiOperation(value = "获取放款签约人列表")
    public IResponse<Object> getLoanAppSignPeopleList(@RequestBody LoanAppSignPeopleListCondition condition) {
        List<LoanAppSignPeopleListCondition> conditionList = new ArrayList<>();
        //1.客户信息含角色：主借人、共借人、担保人
        AfsUser user = SecurityUtils.getUser();
        List<ApplyCustBaseInfo> custList = applyCustBaseInfoService.list(Wrappers.<ApplyCustBaseInfo>query().lambda()
                .eq(ApplyCustBaseInfo::getApplyNo, condition.getApplyNo()));
        ApplyOrderInfo applyOrderInfo = applyOrderInfoService.getOne(Wrappers.<ApplyOrderInfo>query().lambda().eq(ApplyOrderInfo::getApplyNo, condition.getApplyNo()));
        //开票方个人
        ApplyCarInvoice applyCarInvoice = applyCarInvoiceService.getOne(Wrappers.<ApplyCarInvoice>query().lambda()
                .eq(ApplyCarInvoice::getApplyNo, condition.getApplyNo())
                .eq(ApplyCarInvoice::getInvoiceNature,"personal"));
        if(custList !=null && custList.size()>0){
            for(ApplyCustBaseInfo baseInfo :custList ){
                LoanAppSignPeopleListCondition peopleListCondition = new LoanAppSignPeopleListCondition();
                //申请编号
                peopleListCondition.setApplyNo(baseInfo.getApplyNo());
                //客户姓名
                peopleListCondition.setCustName(baseInfo.getCustName());
                //证件号码
                peopleListCondition.setCertNo(baseInfo.getCertNo());
                //角色
                peopleListCondition.setCustRole(baseInfo.getCustRole());
                //手机号码
                peopleListCondition.setTelPhone(baseInfo.getTelPhone());
                //签约人主键id
                peopleListCondition.setId(baseInfo.getId());
                //是否需要重签合同
                if(StrUtil.isBlank(baseInfo.getReappearFlag())){
                    peopleListCondition.setReappearFlag(NO);
                }else{
                    peopleListCondition.setReappearFlag(applyOrderInfo.getReappearFlag());
                }
                //关联合同信息表
                ApplyContractInfo contractInfo = applyContractInfoService.getOne(Wrappers.<ApplyContractInfo>query().lambda()
                        .eq(ApplyContractInfo::getApplyNo, baseInfo.getApplyNo()));
                if(contractInfo !=null){
                    //合同号赋值
                    peopleListCondition.setContractNo(contractInfo.getContractNo());
                }else{
                    peopleListCondition.setContractNo("");
                }
                //关联签约关系表
                if(StrUtil.isNotBlank(peopleListCondition.getContractNo())){
                    List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                            .eq(ApplySignRelation::getCustId, baseInfo.getId())
                            .eq(ApplySignRelation::getBusinessNo,peopleListCondition.getContractNo())
                            .eq(ApplySignRelation::getCustRole,peopleListCondition.getCustRole()));
                    if(signRelationList !=null && signRelationList.size()>0){
                        for(ApplySignRelation relation: signRelationList){
                            if(NO.equals(relation.getStatus()) || StrUtil.isBlank(relation.getStatus())){
                                peopleListCondition.setSignState(NO);
                                break;
                            }else{
                                peopleListCondition.setSignState(YES);
                                peopleListCondition.setSignDate(relation.getUpdateTime());
                            }
                        }
                    }
                }else{
                    peopleListCondition.setSignState(NO);
                }
                conditionList.add(peopleListCondition);
            }
        }
        conditionList.add(applyAppService.getWitnessesInfo(user,condition));
        //业务类型二手车、开票单位性质：个人，获取车商信息
        if(BusinessTypeEnum.OLD_CAR.getCode().equals(applyOrderInfo.getBusinessType()) && applyCarInvoice !=null){
            conditionList.add(applyAppService.geCarDealerInfo(condition,applyCarInvoice));
        }
        return IResponse.success(conditionList);
    }

    @RequestMapping(value = "/getLoanAppContractList", method = RequestMethod.POST)
    @ApiOperation(value = "获取放款合同列表")
    public IResponse<Object> getLoanAppContractList(@RequestBody LoanAppSignPeopleListCondition condition) {
        if(StrUtil.isBlank(condition.getContractNo())){
            return IResponse.fail("合同号不能为空");
        }
        if(condition.getCustId()==null){
            return IResponse.fail("客户id不能为空");
        }
        List<ComAttachmentFile>  fileList = applyAppService.getLoanFileList(condition);
        if(fileList ==null || fileList.size()==0){
            return IResponse.fail("签约文件不存在！");
        }
        return IResponse.success(fileList);
    }

    @RequestMapping(value = "/undoLoanAppSignAgreement", method = RequestMethod.POST)
    @ApiOperation(value = "撤销已签约协议")
    public IResponse<Object> undoLoanAppSignAgreement(@RequestBody ApplyAppSignAgreeMentCondition condition) {
        if(StrUtil.isBlank(condition.getContractNo())){
            return IResponse.fail("合同号不能为空");
        }
        if(condition.getCustomerId() ==null||condition.getCustomerId().length==0){
            return IResponse.fail("客户id不能为空");
        }

        List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                .in(ApplySignRelation::getCustId, Arrays.asList(condition.getCustomerId()))
                .eq(ApplySignRelation::getBusinessNo,condition.getContractNo()));
        if(signRelationList !=null && signRelationList.size()>0){
            for(ApplySignRelation relation:signRelationList){
                List<ApplySignHistory> applySignHistoryList = applySignHistoryService.list(Wrappers.<ApplySignHistory>query().lambda()
                        .eq(ApplySignHistory::getRelationId, relation.getId())
                        .eq(ApplySignHistory::getBusinessNo,condition.getContractNo()));
                if(applySignHistoryList !=null && applySignHistoryList.size()>0){
                    for(ApplySignHistory history :applySignHistoryList){
                        List<ComAttachmentFile> comAttachmentFileList = attachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                                .eq(ComAttachmentFile::getId, history.getFileId()));
                        if(comAttachmentFileList !=null && comAttachmentFileList.size()>0){
                            //1.删除附件信息表数据
                            for(ComAttachmentFile file :comAttachmentFileList){
                                log.info("删除附件信息表对应模版数据"+file);
                                attachmentFileService.removeById(file);
                            }
                        }
                        log.info("删除签约历史信息表对应模版数据"+history);
                        //2.删除签约历史信息表数据
                        applySignHistoryService.removeById(history);

                        //3.删除合同模版合同对应附件信息
                        ComPrintFormManage info = comPrintFormManageService.getOne(Wrappers.<ComPrintFormManage>query().lambda().eq(ComPrintFormManage::getId, history.getTempleId()));
                        if(info !=null){
                            List<ComAttachmentFile> fileList = attachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                                    .eq(ComAttachmentFile::getBusiNo, condition.getContractNo())
                                    .eq(ComAttachmentFile::getAttachmentCode,info.getAscriptionSubClass()));
                            if(fileList !=null && fileList.size()>0){
                                for(ComAttachmentFile file :comAttachmentFileList){
                                    log.info("删除附件信息表对应模版数据"+file);
                                    attachmentFileService.removeById(file);
                                }
                            }
                        }

                    }
                }
                //4.修改合同签约关系表状态：未签约
                relation.setStatus(NO);
                relation.setUpdateTime(null);
                applySignRelationService.updateById(relation);
            }
        }
        return IResponse.success("查询成功");
    }

}
